import { loginAPI, getUserInfoAPI } from '@/api'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'

export default {
  state: {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, preload) {
      state.userInfo = preload
    },
    setRoutes(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
    }
  },
  actions: {
    async login(store, data) {
      store.commit('setToken', await loginAPI(data))
    },
    async getUserInfo(store) {
      const result = await getUserInfoAPI()
      store.commit('setUserInfo', result)
      return result
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('setUserInfo', {})
      resetRouter()
    }
  },
  namespaced: true
}

